package com.rslai.base.tool.servertest;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TestCaseFileFinder {
    private static final Logger logger = LoggerFactory.getLogger(TestCaseFileFinder.class);

    public List<String> getTestCaseList(List<String> testDirs) {
        List filterFilePath = new ArrayList();

        for (String dirs : testDirs) {
            String dirPath = "";
            String matcher = dirs;

            int filePos = dirs.lastIndexOf("/");

            if (filePos >= 0) {
                dirPath = dirs.substring(0, filePos);
                matcher = dirs.substring(filePos + 1);
                matcher = matcher.replace("*", ".*");
            }
            try {
                Enumeration resources = Thread.currentThread().getContextClassLoader().getResources(dirPath);
                while (resources.hasMoreElements()) {
                    URL url = (URL) resources.nextElement();
                    String path = URLDecoder.decode(url.getPath(), "UTF-8");
                    for (String filePath : filterFile(new File(path), matcher))
                        filterFilePath.add(filePath);
                }
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
            }
        }

        return filterFilePath;
    }

    private boolean filePathMatch(String fileName, String matcher) {
        return fileName.matches(matcher);
    }

    private List<String> filterFile(File path, String matcher) {
        List filterFilePath = new ArrayList();
        if (path.isDirectory()) {
            File[] fileList = path.listFiles();
            for (File file : fileList)
                filterFilePath.addAll(filterFile(file, matcher));
        } else if (filePathMatch(path.getName(), matcher)) {
            filterFilePath.add(path.getAbsolutePath());
        }
        return filterFilePath;
    }
}
